//
// Created by tjj on 22-1-7.
//

#include <SDL/SDL.h>
#include <pthread.h>
#include "render_window.h"

static unsigned char* buf = NULL;
static SDL_Overlay* overlay = NULL;
static SDL_Rect drect;

static pthread_t mTid = -1;
static int isQuit = 0;


int window_init(const char* name, int width, int height) {
    SDL_Surface* psscreen;
    SDL_Init(SDL_INIT_EVERYTHING);
    psscreen = SDL_SetVideoMode(width, height, 0, SDL_SWSURFACE);
    SDL_WM_SetCaption(name, NULL);

    /* Create a YUV overlay */
    overlay = SDL_CreateYUVOverlay(width, height, SDL_YUY2_OVERLAY, psscreen);
    buf = overlay->pixels[0];
    drect.x = 0;
    drect.y = 0;
    drect.w = width;
    drect.h = height;

    isQuit = 0;

    return 1;
}

int window_show_image(const char* img, size_t size) {
    if (isQuit) {
        return -1;
    }

    SDL_LockYUVOverlay(overlay);
    memcpy(buf, img, size);
    SDL_UnlockYUVOverlay(overlay);
    SDL_DisplayYUVOverlay(overlay, &drect);

    return 1;
}

static void* routine(void* data){
    SDL_Event event;
    onWindowEvent windowEventFunc = (onWindowEvent) data;

    while (1) // SDL event loop
    {
        SDL_WaitEvent(&event);
        if (event.type == SDL_QUIT) {
            isQuit = 1;
            SDL_Quit();
            windowEventFunc(WINDOW_EVENT_EXIT);
            break;
        } else if (event.type == SDL_MOUSEBUTTONUP) {
            windowEventFunc(WINDOW_EVENT_MOUSE_UP);
        }
    }


    pthread_cancel(mTid);
    pthread_exit(NULL);

    return NULL;
}

void window_event_process(onWindowEvent windowEventFunc) {
    if (windowEventFunc == NULL) {
        return;
    }

    int ret = pthread_create(&mTid, NULL, routine, windowEventFunc);
    if (ret) {
        printf("Error: window_event_process failed !");
    }
}


